<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/ads/models/Ads.php';
require_once 'modules/ads/models/AdsCategory.php';
require_once 'Nine/Auth.php';
require_once 'Nine/Acl.php';
class ads_AdminController extends Nine_Controller_Action_Admin 
{
    
    public function manageAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Nine_Language::translate('Ads Manager'));
        $this->view->menu = array('ads', 'manageads');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        $objAds     = new Models_Ads();
        $objAdsCat  = new Models_AdsCategory();
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        foreach ($data as $id=>$value) {
            $value = intval($value);
            if (1 > $value) {
                continue;
            }
            $objAds->update(array('sorting' => $value), array('ads_id=?' => $id));
            $this->session->adsMessage = array(
                                       'success' => true,
                                       'message' => Nine_Language::translate("Edit sort numbers successfully")
                                   );
        }
       
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->contentDisplayNum;
        } else {
            $this->session->contentDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->contentCondition;
        } else {
            $this->session->contentCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        /**
         * Get all categories
         */
        $allAdsCats = $objAdsCat->buildTree($objAdsCat->getAll(array('sorting ASC'))->toArray());
        
        /**
         * Get all Ads
         */
		$allAds = $objAds->getAllAds($condition, array('sorting ASC', 'ads_id DESC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
        /**
         * Modified ads
         */
        foreach ($allAds as &$ads) {
        	$ads['created_date'] = date($config['dateFormat'],$ads['created_date']);
        }	
        unset($ads);
        
        /**
         * Count all Ads
         */
		$count = count($objAds->getAllAds($condition));

		/**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allAds = $allAds;
        $this->view->allAdsCats = $allAdsCats;
        $this->view->adsMessage = $this->session->adsMessage;
        $this->session->adsMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_ads');
    }
    
    public function newAction()
    {
        $objAds = new Models_Ads();
        $objAdsCat = new Models_AdsCategory();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        
        /**
         * Get all categories
         */
        $allAdsCats = $objAdsCat->buildTree($objAdsCat->getAll(array('sorting ASC'))->toArray());
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new Ads
             */
            $newAds = $data;
        	$newAds['created_date'] = time();
            
         	/**
             * Sorting
             */
            if (null == $newAds['sorting']) {
                unset($newAds['sorting']);
            }
            /**
             * Image
             */
        	if (null != @$newAds['image']) {
        		$newAds['image'] = Nine_Function::getImagePath($newAds['image']);
        	}
        	
            try {
            	/**
                 * Increase all current sortings
                */
                if (1 > $newAds['sorting']) {
                   	$newAds['sorting'] = 1;
                }
                $objAds->increaseSorting($newAds['sorting'], 1);
            	
            	/**
            	 * Insert new ads
            	 */
	            $objAds->insert($newAds);
	            /**
                 * Message
                 */
                $this->session->adsMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Ads is created successfully.')
                        );
	            $this->_redirect('ads/admin/manage');
            }
            catch (Exception $e) {
            	$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
            
        } else {
            $data = array('sorting' => 1);
        }
        /**
         * Prepare for template
         */
        $this->view->allAdsCats = $allAdsCats;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New Ads'));
        $this->view->menu = array('ads', 'newads');
        $this->view->fullPermisison = $this->checkPermission('new_ads', null, '*'); 
    }
    
	public function editAction()
    {
     	if (false == $this->checkPermission('edit_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
    	$id = $this->_getParam('id', false);
     	if (false == $id) {
            $this->_redirect('ads/admin/manage');
        }
		$data = $this->_getParam('data',false);
		if(false != $data) {
			$objAds = new Models_Ads();
			$data['image'] = $this->_getImagePath($data['image']); 
			$objAds->update($data, array('ads_id=?' => $id));
            $this->session->adsMessage = array(
                                       'success' => true,
                                       'message' => Nine_Language::translate("Edit ads successfully")
                                   );
			$this->_redirect('ads/admin/manage');                                   
		} else {
			$objAds = new Models_Ads();
			$data = $objAds->find($id)->toArray();
			$data = current($data);
			if (false == $data) {
				$this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate("Ads doesn't exist.")
                                           );
				$this->_redirect('ads/admin/manage');
			}
		}
		$objAdsCat = new Models_AdsCategory();
		$allAdsCats = $objAdsCat->buildTree($objAdsCat->getAll()->toArray());
		
		$this->view->data = $data;
		$this->view->allAdsCats = $allAdsCats;
		$this->view->adsMessage = $this->session->adsMessage;
		$this->session->adsMessage = null;
		$this->view->headTitle(Nine_Language::translate('Edit Ads'));
		$this->view->menu = array('ads');
		$this->view->fullPermisison = $this->checkPermission('edit_ads', null, '*');
    }

    public function enableAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_ads', null, '*')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manage');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->update(array('enabled' => 1), array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Enable ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT enable this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manage');
    }

    
    
    public function disableAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_ads', null, '*')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manage');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->update(array('enabled' => 0), array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Disable ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT disable this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manage');
    }

   
    
    public function deleteAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_ads')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manage');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->delete(array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Delete ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manage');
    }
    
	private function _getImagePath($path)
    {
        return substr($path, strlen(Nine_Registry::getBaseUrl()));
    }
}